<template>
  <!-- 生成渠道和运营推广链接 -->
  <div class="conten">
    <div class="title">{{ data.title }}第{{ data.chapter_num }}集</div>
    <el-form
      ref="form"
      label-position="top"
      :rules="rules"
      :model="formData"
      label-width="80px"
      class="form"
    >
      <el-form-item
        label="分销方"
        prop="distributor_id"
      >
        <selectPlaylet
          type="miniAppDistributor"
          :is-disabled="type == 3"
          disabled_id="191"
          @result="distributorResult"
        />
      </el-form-item>
      <!-- 运营 -->
      <div v-if="type==3">
        <el-form-item
          label="媒体"
          prop="media_id"
        >
          <el-select
            v-model="formData.media_id"
            style="width:100%;"
            placeholder="请选择"
          >
            <el-option
              v-for="item in optionsList.medialist"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            > </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          v-if="formData.media_id===3 || formData.media_id===1"
          label="投放类型"
          prop="promotion_type"
        >
          <el-radio-group v-model="formData.promotion_type">
            <el-radio
              v-for="(item,index) in promotionList"
              :key="index"
              :label="item.value"
            >{{ item.label }}</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item
          label="账户"
          prop="advertiser"
        >
          <searchSelectMore
            :media_id="formData.media_id"
            type="advertiserList"
            @result="resultAdvertiser"
          />
        </el-form-item>
      </div>
      <!-- 抖音关注加群  小程序开启关注加群设置 并且 app_type==2 才显示  app_type 1微信小程序 2抖音小程序 type==3 生成运营推广 的时候 默认关闭 type 4 投放推广渠道 默认开启-->
      <el-form-item
        v-if="app_type==2 && (rowInfo.follow_switch==1 || rowInfo.group_switch==1)"
        label="抖音关注加群"
        prop="dy_flow_switch"
      >
        <template slot="label">
          抖音关注加群
          <el-tooltip
            class="item"
            effect="dark"
            placement="top"
          >
            <div slot="content">
              <p>开启后，如小程序配置了抖音关注加群功能，则通过本渠道进入的用户会显示抖音关注加群相关功能</p>
            </div>
            <i class="el-icon-question"></i>
          </el-tooltip>
        </template>
        <el-radio-group v-model="formData.dy_flow_switch">
          <el-radio
            v-for="(item,index) in switchStaus"
            :key="index"
            :label="item.value"
          >{{ item.label }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <!--  微信官方播放器组件 -->
      <el-form-item
        v-if="app_type==1 && rowInfo.switch_status==1 "
        label="微信播放器组件"
        prop="player_switch"
      >
        <template slot="label">
          微信播放器组件
          <el-tooltip
            class="item"
            effect="dark"
            placement="top"
          >
            <div
              slot="content"
              class="tooltipLine"
            >
              <p>1、开启后，如短剧在掌娱-播放器管理中已添加启用短剧，则用户通过渠道，进入启用微信播放器短剧后，播放页组件以官方播放器组件为准</p>
              <p>2、关闭后，即使在掌娱-播放器管理中已添加启用短剧，也无效，以自研现有播放器为准</p>
            </div>
            <i class="el-icon-question"></i>
          </el-tooltip>
        </template>
        <el-radio-group v-model="formData.player_switch">
          <el-radio
            v-for="(item,index) in switchStaus"
            :key="index"
            :label="item.value"
          >{{ item.label }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item
        v-if="app_type==1 && formData.player_switch==1"
        label="拼团-解锁全集"
        prop="group_buy_switch"
      >
        <template slot="label">
          拼团-解锁全集
          <el-tooltip
            class="item"
            effect="dark"
            placement="top"
          >
            <div
              slot="content"
              class="tooltipLine"
            >
              <p>1、开启后，如短剧设置了拼团解锁，则唤起充值模板时，会自动添加拼团档位</p>
              <p>2、关闭后，不显示拼团档位</p>
            </div>
            <i class="el-icon-question"></i>
          </el-tooltip>
        </template>
        <el-radio-group v-model="formData.group_buy_switch">
          <el-radio
            v-for="(item,index) in switchStaus"
            :key="index"
            :label="item.value"
          >{{ item.label }}</el-radio>
        </el-radio-group>
      </el-form-item>

      <!--  微信小程序开启流量主配置 -->
      <el-form-item
        v-if="rowInfo.mini_app_ad_switch==1"
        label="广告主流量"
        prop="ad_switch"
      >
        <template slot="label">
          广告主流量
          <el-tooltip
            class="item"
            effect="dark"
            placement="top"
          >
            <div slot="content">
              <p>开启后，如小程序配置了广告流量主功能，满足广告的受众用户进入小程序后会显示广告</p>
            </div>
            <i class="el-icon-question"></i>
          </el-tooltip>
        </template>
        <el-radio-group v-model="formData.ad_switch">
          <el-radio
            v-for="(item,index) in switchStaus"
            :key="index"
            :label="item.value"
          >{{ item.label }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item
        v-if="formData.ad_switch==1"
        label="优先显示激励广告"
        prop="first_reward_ad"
      >
        <template slot="label">
          优先显示激励广告
          <el-tooltip
            class="item"
            effect="dark"
            placement="top"
          >
            <div slot="content">
              <p>如设置是，则该渠道进入所有用户到付费集优先显示解锁激励广告弹窗，不主动弹出充值模板及充值挽留</p>
            </div>
            <i class="el-icon-question"></i>
          </el-tooltip>
        </template>
        <el-radio-group v-model="formData.first_reward_ad">
          <el-radio
            v-for="(item,index) in switchStaus"
            :key="index"
            :label="item.value"
          >{{ item.label }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item
        label="渠道名称"
        prop="channel_name"
      >
        <el-input
          v-model="formData.channel_name"
          placeholder="请输入内容"
        ></el-input>
      </el-form-item>
      <el-form-item
        label="开始付费剧集"
        prop="start_pay_chapter"
        class="lineHeight"
      >
        <el-select
          v-model="formData.start_pay_chapter"
          clearable
          placeholder="请选择短剧"
          style="width:100%;"
        >
          <el-option
            v-for="item in chapterList"
            :key="item.id"
            :label="item.value"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        label="初始定价"
        prop="pay_coin"
      >
        <div class="payinput rowFlex">
          <el-input
            v-model="formData.pay_coin"
            oninput="value=value.replace(/^\D*(\d*(?:\.\d{0,2})?).*$/g, '$1')"
            style="width:380px;"
          ></el-input>
          <div class="unit">虚拟币/集</div>
        </div>
      </el-form-item>
      <div
        v-if="this.formData.step.length > 0"
        class="step"
      >
        <div class="messagesActive">
          <div class="icon">
            <i class="el-icon-warning"></i>
          </div>
          <div class="text">
            设置阶梯价的集数将优先用阶梯价定价，未设置阶梯价集数统一用初始定价
          </div>
        </div>
        <div class="step_list">
          <el-row class="elrow">
            <div
              v-for="(item, index) in formData.step"
              :key="index"
              style="display: flex; align-items: center;"
            >
              <span>
                集数
              </span>
              <el-col :span="6">
                <!--  -->
                <el-form-item
                  :prop="'step.' + index + '.start_chapter'"
                  :rules="[{ required: true, validator:validatestart_chapter, trigger: 'blur' },
                           { required: true, message: '请输入', trigger: 'blur'},
                           { required: true, validator:(rule, value, callback) => {
                             if(index == 0) {
                               callback()
                             }else {
                               if (formData.step[index-1].end_chapter * 1 >= value * 1) {
                                 callback(onerr('本条起始集数需>上条结束集数'))
                               }else {
                                 callback()
                               }
                             }
                           } , trigger: 'blur' },{
                             required: true, validator:(rule, value, callback) => {
                               if (chapterList.length*1 < value * 1) {
                                 callback(onerr('起始集数≤本剧最大集数'))
                               }else {
                                 callback()
                               }
                             } , trigger: 'blur'
                           }]"
                >
                  <el-input
                    v-model="item.start_chapter"
                    placeholder="起始集数"
                    style="width: 150px;"
                    type="number"
                    @input="item.start_chapter = item.start_chapter.replace(/\D|^0/g,'') "
                  > </el-input>

                </el-form-item>
              </el-col>
              <span>-</span>
              <el-col :span="6">
                <el-form-item
                  :prop="'step.' + index + '.end_chapter'"
                  :rules="[{ required: true, message: '请输入', trigger: 'blur'},
                           { required: true, validator:(rule, value, callback) => {
                             if ( item.start_chapter * 1 > value * 1) {
                               callback(onerr('结束集数需≥起始集数'))
                             }else {
                               callback()
                             }
                           } , trigger: 'blur' },
                           {
                             required: true, validator:(rule, value, callback) => {
                               if (chapterList.length*1 < value * 1) {
                                 callback(onerr('结束集数需≤本剧最大集数'))
                               }else {
                                 callback()
                               }
                             } , trigger: 'blur'
                           }]"
                >
                  <el-input
                    v-model="item.end_chapter"
                    placeholder="结束集数"
                    style="width: 150px;"
                    type="number"
                    @input="item.end_chapter = item.end_chapter.replace(/\D|^0/g,'') "
                  > </el-input>
                </el-form-item>
              </el-col>
              <span>阶梯价</span>
              <el-col :span="6">
                <el-form-item
                  :prop="'step.' + index + '.step_coin'"
                  :rules="[
                    { required: true, validator:validateCoin, trigger: 'blur',playlet_id:formData.playlet_id},
                    { required: true, message: '请输入', trigger: 'blur'}
                  ]"
                >
                  <el-input
                    v-model="item.step_coin"
                    placeholder="虚拟币/集"
                    style="width: 150px;"
                    type="number"
                    @input="item.step_coin = item.step_coin.replace(/\D|^0/g,'') "
                  > </el-input>
                </el-form-item>
              </el-col>
              <el-col
                :span="2"
                style="height: 100%;"
              >
                <div style="height: 100%; display: flex; align-items: center;">
                  <i
                    style="margin-left: 10px; font-size: 20px; color: #06c021; cursor: pointer"
                    class="el-icon-remove-outline"
                    @click="onDelStep(index)"
                  ></i>
                </div>
              </el-col>
            </div>
          </el-row>
        </div>
        <el-button
          class="addStep"
          @click="onAddStep"
        >
          <i
            class="el-icon-plus"
            style="font-weight: bold;"
          ></i><span>添加阶梯价</span></el-button>
      </div>
      <el-button
        v-else
        class="step_button"
        @click="onAddStep"
      > <i
          class="el-icon-plus"
          style="font-weight: bold;"
        ></i><span>添加阶梯价</span></el-button>
      <el-form-item prop="pay_template_id">
        <template slot="label">
          <span>充值模版:</span>
          <el-tooltip
            class="item"
            effect="dark"
            placement="top"
          >
            <div slot="content">
              <p>1、充值模板请在充值档位管理中添加</p>
              <p style="margin-top:10px;">2、如需修改渠道充值模板，可在渠道管理-修改充值模板中调整</p>
            </div>
            <i
              class="el-icon-question el-icon--right"
              style="font-size:14px;"
            ></i>
          </el-tooltip>
        </template>
        <div style="display: flex;align-items: center;">
          <el-select
            v-model="formData.pay_template_id"
            clearable
            filterable
            remote
            style="width:99%;"
            placeholder="请选择充值模版"
            :remote-method="requestTemplateList"
            @change="selectChangeTemplate"
          >
            <el-option
              v-for="(item,index) in templateList"
              :key="index"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </div>
      </el-form-item>
      <!-- 显示条件 微信小程序下 运营和推广新增  显示前置条件：小程序管理-引流设置中，开启引流且为公众号引流，显示该项，如未开启或未设置公众号引流，则不显示该项-->
      <el-form-item
        v-if="app_type==1 && rowInfo.flow_config==1"
        label="引流规则"
        prop="flow_rule_id"
      >
        <el-select
          v-model="formData.flow_rule_id"
          clearable
          filterable
          remote
          placeholder="请选择引流规则"
          style="width:100%;"
        >
          <el-option
            v-for="(item,index) in selectList"
            :key="index"
            :label="item.label+' / '+item.value"
            :value="Number(item.value)"
          ></el-option>
        </el-select>
        <div class="redText">配置后会显示，不配置不显示引流</div>
      </el-form-item>
      <el-form-item
        v-if="app_type==2 && type != 3"
        label="用途"
        prop="purpose"
      >
        <el-select
          v-model="formData.purpose"
          clearable
          filterable
          remote
          placeholder="请选择用途"
          style="width:100%;"
        >
          <el-option
            v-for="(item,index) in optionsList.purpose"
            :key="index"
            :label="item.label"
            :value="Number(item.value)"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <div class="pay_template">
          <div class="pay_template_header">
            <div
              class="text"
              :class="activeText==1?'activeText':''"
              @click="(activeText=1,renderTemplateList=templatePreviewData.first_ist)"
            >首充模板</div>
            <div
              class="text"
              :class="activeText==2?'activeText':''"
              @click="(activeText=2,renderTemplateList=templatePreviewData.repeat_list)"
            >复充模板</div>
          </div>
          <div class="pay_template_main">
            <div class="content rowFlex rowCenter">
              <newRechargeTemplate :list="renderTemplateList"></newRechargeTemplate>
            </div>
          </div>
        </div>
      </el-form-item>

      <Consumption
        v-if="templatePreviewData.first_ist && (formData.pay_coin|| formData.step) && formData.start_pay_chapter && chapterList.length"
        :rule="formData.step"
        :template="templatePreviewData.first_ist"
        :initial="formData.pay_coin *1"
        :start="formData.start_pay_chapter*1"
        :total="chapterList.length*1"
      >
      </consumption>
    </el-form>
    <div class="dialog-footer rowFlex">
      <div class="btns">
        <el-button
          class="btn"
          @click="close"
        >取 消</el-button>
        <el-button
          class="btn"
          type="primary"
          :loading="btnLoading"
          @click="onSubmit"
        >确 定</el-button>
      </div>
    </div>
    <changeTemplateMsg
      v-if="shwoTemplateMsg"
      :show.sync="shwoTemplateMsg"
      :row-info="rowInfo"
      :msg="templateMsg"
    />
  </div>
</template>

<script>
import Consumption from '@/components/Consumption'
import { promotionalLinks } from '@/api/appContent/theater'
import { commonData } from '@/api/common'
import { validateCoin, validateStart, reqeustPayInfo } from '@/utils/index'
import searchSelectMore from '@/common/component/form/searchSelectMore.vue'
import newRechargeTemplate from '@/common/component/newRechargeTemplate.vue'
import { templatePreview } from '@/api/channel'
import { mapState, mapMutations, mapActions } from 'vuex'
import changeTemplateMsg from '@/views/channel/component/changeTemplateMsg.vue'
export default {
  components: {
    searchSelectMore,
    newRechargeTemplate,
    changeTemplateMsg,
    Consumption
  },
  props: {
    // type 3 生成运营推广链接 4 生成 渠道推广链接
    data: {
      type: Object,
      default: {}
    },
    rowInfo: {
      type: Object,
      default: {}
    },
    type: {
      type: String,
      default: ''
    }
  },
  computed: {
    ...mapState('user', ['menu']),
    ...mapState('user', ['routerItem'])
  },
  data() {
    var validatestart_chapter = (rule, value, callback) => {
      if (value < this.formData.start_pay_chapter * 1) {
        callback(new Error('起始收费集数需≥开始付费剧集'))
      } else {
        callback()
      }
    }
    return {
      validatestart_chapter: validatestart_chapter,
      validateCoin: validateCoin,
      loading: false,
      btnLoading: false,
      shwoTemplateMsg: false,
      templateMsg: '',
      activeText: 1,
      app_type: 1,
      chapterList: [],
      templateList: [],
      renderTemplateList: [],
      templatePreviewData: {},
      selectList: [],
      switchStaus: [
        {
          label: '关闭',
          value: 2
        },
        {
          label: '开启',
          value: 1
        }
      ],
      formData: {
        media_id: '',
        mini_app_id: window.localStorage.getItem('mini_app_id'),
        playlet_id: '',
        chapter_id: '',
        channel_name: '',
        advertiser: '',
        flow_rule_id: '',
        purpose: '', // 抖音 - 运营 - 用途
        promotion_type: 1, // 推广类型  1小程序直投，2企微投放
        dy_flow_switch: 2, // 抖音加群 1 开启 2关闭
        player_switch: 2, // 官方播放器开关 1 开 2 关
        group_buy_switch: 2, // 拼团开关
        ad_switch: 2, // 广告主 1 开启 2关闭
        pay_coin: '',
        distributor_id: '', // 分销方
        pay_template_id: '',
        start_pay_chapter: '',
        step: [],
        first_reward_ad: 2
      },
      advertiser: {},
      title: '',
      optionsList: {
        playletList: [],
        medialist: [],
        purpose: []
      },
      promotionList: [
        { label: '企微直投', value: 2 },
        { label: '小程序直投', value: 1 }
      ],
      rules: {
        channel_name: [{ required: true, message: '请输入', trigger: 'blur' }],
        pay_template_id: [{ required: true, message: '请选择充值模版', trigger: 'change' }],
        advertiser: [{ required: true, message: '请选择账户', trigger: 'blur' }],
        distributor_id: [{ required: true, message: '请选择分销方', trigger: 'blur' }],
        media_id: [{ required: true, message: '请输入', trigger: 'blur' }],
        pay_coin: [
          { required: true, message: '输入定价', trigger: 'blur' },
          { required: true, validator: validateCoin, trigger: 'blur' }
        ],
        dy_flow_switch: [{ required: true, message: '请选择', trigger: 'change' }],
        ad_switch: [{ required: true, message: '请选择', trigger: 'change' }],
        start_pay_chapter: [
          { required: true, message: '收费剧集最小为1', trigger: 'blur' },
          { required: true, validator: validateStart, trigger: 'change' }
        ],
        purpose: [{ required: true, message: '请选择', trigger: 'change' }],
        first_reward_ad: [{ required: true, message: '请选择是否优先显示激励广告', trigger: 'blur' }]
      }
    }
  },

  created() {
    this.resize_commonDataList({ type: 'flowRuleDown' })
  },
  async mounted() {
    this.selectList = await this.requestCommonData({ type: 'flowRuleDown', mini_app_id: window.localStorage.getItem('mini_app_id') })
    if (this.type == 4) {
      // 运营推广渠道
      this.formData.dy_flow_switch = 2
    } else {
      this.formData.dy_flow_switch = 1
    }
    const selectApp = this.menu.find((item) => item.id == window.localStorage.getItem('mini_app_id'))
    if (selectApp) {
      this.app_type = Number(selectApp.app_type)
    } else {
      window.location.reload()
    }
    this.onGetpurposeList()
    this.onGetMediaList()
    reqeustPayInfo()
    this.requestTemplateList()
    this.reqeustChapter(this.data.playlet_id)
    this.formData.playlet_id = this.data.playlet_id
    this.formData.chapter_id = this.data.chapter_id
    this.formData.pay_coin = this.rowInfo.pay_coin
    this.formData.start_pay_chapter = this.rowInfo.start_pay_chapter * 1
    this.rules.pay_coin = [
      { required: true, message: '输入定价', trigger: 'blur' },
      { required: true, validator: validateCoin, trigger: 'blur', playlet_id: this.formData.playlet_id }
    ]
    console.log(this.rowInfo.start_pay_chapter)
  },
  methods: {
    ...mapMutations('common', ['resize_commonDataList']),
    ...mapActions('common', ['requestCommonData']),
    onPayTemplate(value) {},
    async onGetpurposeList() {
      const res = await commonData({ type: 'purpose' })
      if (res.status_code === 1) {
        this.optionsList.purpose = res.data.data
      }
    },
    onerr(str) {
      return new Error(str)
    },
    onDelStep(index) {
      this.formData.step.splice(index, 1)
    },
    onAddStep() {
      this.formData.step.push({
        start_chapter: '',
        end_chapter: '',
        coin: ''
      })
    },
    // 模版详情
    selectChangeTemplate(value) {
      templatePreview({ template_id: value }).then((res) => {
        if (res.status_code == 1) {
          this.templatePreviewData = res.data.data
          this.renderTemplateList = this.templatePreviewData.first_ist
        }
      })
    },
    requestTemplateList(value) {
      commonData({ type: 'rechargeTemplate', mini_app_id: this.formData.mini_app_id, value }).then((res) => {
        if (res.data.data.length > 0) {
          this.templateList = res.data.data
        }
      })
    },
    // 分销方
    distributorResult(value) {
      this.formData.distributor_id = value
    },
    close() {
      this.$emit('cancel')
    },
    reqeustChapter(value) {
      commonData({ type: 'playletChapter', value: value }).then((res) => {
        if (res.status_code === 1) {
          this.chapterList = res.data.data
        }
      })
    },
    async onSubmit() {
      const params = {
        ...this.formData,
        ...this.formData.advertiser,
        ...this.data,
        playlet_name: this.data.title || '',
        advertiser: null,
        channel_type: this.type
      }
      if (this.type == 4) {
        params.media_id = 0
      }
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.btnLoading = true
          promotionalLinks(params).then(
            (res) => {
              this.btnLoading = false
              if (res.status_code == 1) {
                this.$message.success(res.msg)
                this.$emit('ok')
              }
            },
            (err) => {
              this.templateMsg = err
              this.shwoTemplateMsg = true
              this.btnLoading = false
            }
          )
        } else {
          console.log('error submit!!')
          return false
        }
      })
      this.loading = false
    },
    async onGetMediaList() {
      console.log(this.routerItem, '--------------')
      const res = await commonData({
        type: 'media',
        app_type: this.routerItem.app_type
      })
      if (res.status_code === 1) {
        this.optionsList.medialist = res.data.data
        this.formData.media_id = res.data.data[0].value
      }
    },
    resultAdvertiser(value) {
      console.log(value, '123')
      this.formData.advertiser = value
    },
    onAdvertiserChange(value) {}
  }
}
</script>
<style lang="scss" scoped>
.pay_template {
  width: 100%;
  border: 1px solid #ebeef5;
  // margin-top: px;
  .pay_template_header {
    width: 100%;
    height: 40px;
    display: flex;
    align-items: center;
    background: #f7f8fa;
    justify-content: space-around;
    .text {
      display: flex;
      justify-content: center;
      font-size: 14px;
      font-family: PingFangSC-Medium, PingFang SC;
      font-weight: 600;
      color: #333333;
      cursor: pointer;
    }
    .activeText {
      color: #06c261;
      border-bottom: 2px solid #06c261;
    }
  }
  .qrImage {
    width: 200px;
    height: 200px;
  }
  .pay_template_main {
    width: 100%;
    display: flex;
    justify-content: space-between;
    .content {
      width: 100%;
      padding: 15px !important;
    }
  }
}
.conten {
  width: 675px;
  ::v-deep .el-form-item__label {
    font-weight: 600;
  }
  .contentMain {
    // padding: 20px;
  }
  .title {
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 20px;
    font-size: 16px;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 600;
    color: #333333;
    line-height: 20px;
    margin-bottom: 10px;
    padding-top: 30px;
  }
  .unit {
    display: flex;
    width: 70px;
    margin-left: 10px;
  }
  .form {
    padding: 20px;
    padding-bottom: 100px;
    .step {
      margin-bottom: 18px;
      background: #f7f8fa;
      border-radius: 3px;
      padding: 16px;
      ::v-deep.el-form-item__error {
        white-space: nowrap;
      }
      .elrow {
        ::v-deep.el-col-10 {
          width: 100px;
          margin: 0 8px;
        }
        span {
          flex-shrink: 0;
          margin: 0 5px;
        }
        ::v-deep.el-form-item.is-required.el-form-item--small {
          margin: 10px 0;
        }
      }
    }
  }
}
.step_button {
  margin-bottom: 10px;
}
.messagesActive {
  margin: 0;
}
.addStep {
  margin-top: 10px;
}
</style>